package com.company.app.events;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import com.company.app.entities.FrameValueObject;
import com.company.app.entities.ImageValueObject;
import com.company.app.services.FileChooserHandler;
import com.company.app.services.InputPathHandler;
import com.company.app.services.OpenPhotoHandler;
import com.company.app.constants.*;

public class InputPathListener {
  public void showInputPathDialog(FrameValueObject frameJO) {
    JTextField directoryField = new JTextField(20);
    JButton openButton = new JButton(Sentence.find_open_text);
    InputPathHandler inputHandler = new InputPathHandler();
    OpenPhotoHandler photoHandler = new OpenPhotoHandler();
    FileChooserHandler fileHandler = new FileChooserHandler();

    openButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        String paramPath = directoryField.getText().trim();
        if (paramPath.isEmpty()) {
          popUpError(inputHandler, frameJO.getFrame(), Sentence.tip_text, Sentence.err_text);
          return;
        }

        File fi = new File(paramPath);
        if (!(fi.exists())) {
          popUpError(inputHandler, frameJO.getFrame(), Sentence.hint_text, Sentence.err_text);
          return;
        }

        ImageValueObject vo = new ImageValueObject();

        if ((fi.isDirectory())) {// 若为文件夹
          vo = inputHandler.loadImgsFromDir(fi);
        } else if (fi.isFile()) {// 若为文件
          vo = fileHandler.getImgByFilePath(fi.getAbsolutePath());
        }

        if (vo == null) {
          System.out.println(this + " No any pictures");
          popUpError(inputHandler, frameJO.getFrame(), Sentence.notice_text, Sentence.err_text);
          return;
        }
        exectuteOpen(frameJO, vo, openButton, photoHandler);
      }
    });

    directoryField.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        openButton.doClick();
      }
    });

    inputHandler.showOptPane(frameJO, openButton, directoryField);
  }

  public void exectuteOpen(FrameValueObject frameJO, ImageValueObject vo, JButton openButton,
      OpenPhotoHandler photoHandler) {

    frameJO.setImageValObj(vo);
    photoHandler.openPhoto(frameJO, vo.getCurrentPath());

    Window window = SwingUtilities.getWindowAncestor(openButton);
    if (window instanceof JDialog) {
      JDialog dialog = (JDialog) window;
      dialog.dispose();// 关闭对话框
    }
  }

  public void popUpError(InputPathHandler inputHandler, JFrame frame, String errStr, String title) {
    inputHandler.showErrorDialog(errStr, frame, title);
  }

}